﻿using HslCommunication;
using HslCommunication.Profinet.Omron;
using HslCommunication.Profinet.Siemens;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace paraInterface
{
    internal class omronFinsUDPPLC:PLC//--箱式炉
    {

        OmronFinsUdp omronPLC { get; set; }

        public override bool InitPLC()
        {
            if (IsIP(IP))
            {
                omronPLC = new OmronFinsUdp(IP,9600);
                omronPLC.DNA = 0;
                omronPLC.DA1 = 0;
                omronPLC.SNA = 0;
                omronPLC.SA1 = (byte)SUB;
                isRealPLC=true;
            }
            return isRealPLC;
        }
        public override bool SendData2PLC(jsonData data)//需要将数据进行解析
        {
            if (data.PARAMS.Length < 44)
                return false;
            short[] v = new short[data.PARAMS.Length];
            for (int i = 0; i < data.PARAMS.Length; i++)
            {
                v[i] = Convert2PLCData(data.PARAMS[i]);
            }
            return WriteWords(ADD, v);
        }

        private  bool WriteWords(string sStartAdd, short[] sValue)
        {
            OperateResult res = omronPLC.Write(sStartAdd, sValue);
            if (res.IsSuccess)
                pubcls.WriteLog("数据写入成功\n数据:" + sValue.ToJsonString());
            else
                pubcls.WriteLog("数据写入失败\n数据:" + sValue.ToJsonString());
            return res.IsSuccess;
        }

        private short Convert2PLCData(ParameterData para)
        {
            if (double.TryParse(para.TBGD_UPPER_LIMIT, out double x))
            {
                if (para.TBCD_UNIT.ToLower() == "min")
                    return Convert.ToInt16(x.ToString(), 16);
                else if (para.TBCD_UNIT == "%")
                    return (short)(x * Math.Pow(10, 3));
                else
                    return (short)x;
            }
            return 0;
        }

    }
}
